package com.fc.mall.portal.config;

import com.fc.mall.exception.ServiceException;
import com.fc.mall.portal.service.ConfigService;
import com.fc.mall.portal.wechat.dto.WxConfig;
import com.fc.mall.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * 微信服务商支付配置
 * Created by Sunny on 2019/8/13.
 */
@Configuration
public class WspConfig {

    @Autowired
    ConfigService configService;

    @Value("${wxpay.isWSP}")
    private String isWsp;

    @Value("${wxpay.wspAppId}")
    private String wspAppId;

    @Value("${wxpay.wspMchId}")
    private String wspMchId;

    @Value("${wxpay.wspSecrect}")
    private String wspSecrect;

    @Value("${wxpay.wspKey}")
    private String wspKey;

    @Value("${app.name}")
    public String appName;



    @Bean
    public WxConfig wxConfig()
    {
        String merchanAppId = configService.getRequiredConfig(Constants.SysPropertyConfigName.APPID.getName());
        String metchantMchId = configService.getRequiredConfig(Constants.SysPropertyConfigName.MCHID.getName());
        String notifyUrl = configService.getRequiredConfig(Constants.SysPropertyConfigName.NOTIFYURL.getName());
        String appSecrect = configService.getRequiredConfig(Constants.SysPropertyConfigName.APPSECRECT.getName());
        String payKey = configService.getRequiredConfig(Constants.SysPropertyConfigName.PAYKEY.getName());
        String certUrl = configService.getRequiredConfig(Constants.SysPropertyConfigName.CERT.getName());
        byte[] certByte;
        try {
            InputStream cert = new URL(certUrl).openStream();
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = cert.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            certByte = swapStream.toByteArray();
            if(Boolean.parseBoolean(isWsp))
            {
                return new WxConfig(wspAppId,
                        wspMchId,
                        merchanAppId,
                        metchantMchId,
                        notifyUrl,
                        wspSecrect,
                        wspKey,
                        certByte);
            }
            return new WxConfig(merchanAppId, metchantMchId, notifyUrl, appSecrect, payKey,certByte);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }

    }
}
